<template>
  <div class="mass-preventionorg-wrapper">
    <p class="title">综合条件查询</p>
    <div class="form-search-area">
      <el-form :inline="true" :model="formInline" size="medium" class="demo-form-inline">
        <el-form-item label="组织名称">
          <el-input v-model="formInline.groupNameLike" placeholder="请输入组织名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="组织类型">
          <el-select v-model="formInline.groupType" placeholder="请选择组织类型" clearable>
            <el-option
              v-for="(item) in DICY.groupType"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务指导部门">
          <el-input v-model="formInline.guideDepartLike" placeholder="请输入业务指导部门" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="medium" @click="searchOrg">查询</el-button>
          <el-button size="medium" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="right-btn-area">
        <el-button size="medium" type="primary" @click="popNewAddDialog">新增组织</el-button>
        <el-button size="medium">导入</el-button>
        <el-button size="medium">导出</el-button>
        <el-button size="medium" @click="batchDeletion">批量删除</el-button>
      </div>
    </div>
    <!-- 表格 开始-->
    <div class="table-area clearfix">
      <el-table :data="tableData" ref="multipleTable" @selection-change="selectionChange" v-loading="loading" stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" width="50">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="组织名称" prop="groupName"></el-table-column>
        <el-table-column label="组织类型" prop="groupType">
          <template slot-scope="scope">{{convertKeyToVal (scope.row.groupType, DICY.groupType)}}</template>
        </el-table-column>
        <el-table-column label="业务指导部门" prop="guideDepart"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" icon="el-icon-view" @click="viewDetail(scope.row.id)">查看</el-link>
            <el-link type="success" :underline="false" icon="el-icon-edit" @click="editDetail(scope.row.id)">编辑</el-link>
            <el-link type="danger" :underline="false" icon="el-icon-delete" @click="deleteDetail(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="paging-self"
        background
        :current-page.sync="currentPage"
        @current-change="pageChange"
        layout="total, prev, pager, next"
        :total="totalCount">
      </el-pagination>
    </div>
    <!-- 表格 结束-->
    <!-- 对话框 开始 -->
    <el-dialog title="群防群治组织" :visible.sync="dialogFormVisible" width="810px" @closed="closeDialog">
      <el-form :model="dialogForm" class="dialog-form-comot" :disabled="dialogMode===CNST.READ_MODE" :rules="rules" ref="ruleDialog">
        <el-row>
          <el-col :span="12">
            <el-form-item label="组织名称" label-width="106px" prop="groupName">
              <el-input v-model="dialogForm.groupName" placeholder="请输入组织名称" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属辖区" label-width="106px" prop="personName">
              <el-cascader
                v-model="dialogForm.region"
                :options="options"
                @change="handleChange"
                placeholder="请选择所属辖区">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="组织类型" label-width="106px" prop="groupType">
              <el-select v-model="dialogForm.groupType" placeholder="请选择组织类型" clearable>
                <el-option
                  v-for="(item) in DICY.groupType"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织层级" label-width="106px" prop="groupLevel">
              <el-select v-model="dialogForm.groupLevel" placeholder="请选择组织层级" clearable>
                <el-option
                 v-for="(item) in DICY.orgLevel"
                 :key="item.code"
                 :label="item.name"
                 :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="业务指导部门" label-width="106px" prop="guideDepart">
              <el-input v-model="dialogForm.guideDepart" placeholder="请输入业务指导部门" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员数量" label-width="106px" prop="personCount">
              <el-input-number v-model="dialogForm.personCount" :min="0" label="人员数量" controls-position="right" placeholder="请输入人员数量"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="主要职能" label-width="106px" prop="mainFunctions">
              <el-input type="textarea" v-model="dialogForm.mainFunctions" :rows="3" placeholder="请输入主要职能" autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrg" v-if="dialogMode!==CNST.READ_MODE">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 对话框 结束 -->
  </div>
</template>

<script>

import { getGovernGroupList, addGovernGroup, getGovernGroupDetail, updateGovernGroupDetail, deleteGovernGroup, deleteGovernGroupBatch } from '@/api/baseBusiness'
import { deepClone } from '@/utils'
import { mapState } from 'vuex'

export default {
  name: 'MassPreventionOrg',
  data () {
    return {
      formInline: {
        groupNameLike: '',
        groupType: '',
        guideDepartLike: ''
      },
      loading: false,
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      totalCount: 0,
      dialogFormVisible: false,
      dialogForm: {
        groupName: '',
        groupType: '',
        groupLevel: '',
        guideDepart: '',
        personCount: '',
        mainFunctions: ''
      },
      rules: {
        groupName: [
          { required: true, message: '请输入组织名称', trigger: 'blur' },
          { max: 100, message: '长度在 50 个汉字以内', trigger: 'blur' }
        ],
        groupType: [
          { required: true, message: '请选择组织类型', trigger: 'change' }
        ],
        groupLevel: [
          { required: true, message: '请选择组织层级', trigger: 'change' }
        ],
        guideDepart: [
          { required: true, message: '请输入业务指导部门', trigger: 'blur' }
        ],
        personCount: [
          { required: true, message: '请输入人员数量', trigger: 'blur' }
        ],
        mainFunctions: [
          { required: true, message: '请输入主要职能', trigger: 'blur' }
        ]
      },
      dialogMode: '', // 对话框的状态，新增，查看，编辑
      curId: '', // 点击查看或编辑的当前列表项的id
      options: this.DICY.jilian
    }
  },
  computed: {
    ...mapState([
      'areaId'
    ])
  },
  methods: {
    convertKeyToVal (code, arr) {
      arr = Array.isArray(arr) ? arr : []
      let resArr = arr.filter((item) => {
        return item.code === code
      })
      if (resArr.length === 0) {
        return ''
      }
      return resArr[0].name
    },
    // 查询
    searchOrg () {
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    // 重置
    resetSearch () {
      for (let key in this.formInline) {
        this.$set(this.formInline, key, '')
      }
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    // 新增
    popNewAddDialog () {
      this.dialogFormVisible = true
      this.dialogMode = this.CNST.ADDNEW_MODE
    },
    // 批量删除
    batchDeletion () {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请勾选要删除的项!'
        })
      } else {
        var ids = this.multipleSelection.map((item) => {
          return item.id
        }).join(',')
        this.$confirm('确定删除, 是否继续?', '批量删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteGovernGroupBatch({ ids }).then((res) => {
            this.$message({
              type: 'success',
              message: '批量删除成功!'
            })
            this.getOrgListAndShow()
          })
        })
      }
    },
    // 选中
    selectionChange (valArr) {
      this.multipleSelection = valArr
    },
    // 查看
    viewDetail (id) {
      this.dialogMode = this.CNST.READ_MODE
      this.dialogFormVisible = true
      getGovernGroupDetail({ id }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    // 修改
    editDetail (id) {
      this.dialogMode = this.CNST.EDIT_MODE
      this.dialogFormVisible = true
      this.curId = id
      getGovernGroupDetail({ id }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    // 删除
    deleteDetail (id) {
      this.$confirm('确定删除, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        deleteGovernGroup({ id }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getOrgListAndShow()
        })
      })
    },
    // 翻页
    pageChange (curPage) {
      this.currentPage = curPage
      this.getOrgListAndShow()
    },
    // 确定按钮提交
    submitOrg () {
      this.$refs.ruleDialog.validate((valid) => {
        if (valid) {
          // 验证通过
          // -----------------
          let requestData = deepClone(this.dialogForm)
          if (this.dialogMode === this.CNST.ADDNEW_MODE) {
            // 新增
            requestData.areaId = this.areaId
            addGovernGroup(requestData).then((res) => {
              this.$message({
                message: '新增群防群治组织成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          } else if (this.dialogMode === this.CNST.EDIT_MODE) {
            // 修改
            requestData.id = this.curId
            updateGovernGroupDetail(requestData).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          }
          // -----------------
        } else {
          return false
        }
      })
    },
    closeDialog () {
      // 当前点击查看或编辑列表项的id置空
      this.curId = ''
      // 弹框关闭后重置表单验证
      this.$refs.ruleDialog.resetFields()
      // 清空弹框内表单数据
      for (let key in this.dialogForm) {
        this.dialogForm[key] = ''
      }
    },
    handleChange (value) {
      console.log(value)
    },
    // 查询列表
    async getOrgListAndShow () {
      try {
        this.loading = true
        let requestData = {
          page: this.currentPage,
          areaId: this.areaId,
          ...deepClone(this.formInline)
        }
        var res = await getGovernGroupList(requestData)
        this.tableData = res.data.queryResult
        this.totalCount = res.data.totalCount
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    showToDialog (data) {
      for (let key in data) {
        if (this.dialogForm.hasOwnProperty(key)) {
          this.dialogForm[key] = data[key]
        }
      }
    }
  },
  mounted () {
    this.getOrgListAndShow()
  }
}
</script>

<style lang="scss" scoped>
.mass-preventionorg-wrapper {
  background-color: #ffffff;
  margin-top: 12px;
  border-radius: 4px;
  box-shadow: 10px 10px 22px -2px #d2d6da;
  padding: 20px;
  .title {
    margin: 0;
    font-size: 15px;
    color: #333333;
    margin-bottom: 10px;
  }
  .form-search-area {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }
  .table-area {
    .el-link {
      margin-right: 13px;
    }
    .el-pagination.paging-self {
      margin-top: 20px;
      float: right;
    }
  }
  .el-form.dialog-form-comot {
    .el-form-item {
      .el-cascader,.el-select,.el-input-number {
        width: 100%;
      }
    }
  }
}
</style>
